package com.atguigu.daijia.customer.service.impl;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import com.atguigu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
/**
 * CustomerInfoServiceImpl类是顾客信息服务的实现类
 * 继承自ServiceImpl，用于处理与顾客信息相关的业务逻辑
 */
@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {
    // 注入微信小程序服务，用于与微信接口交互
    @Autowired
    private WxMaService wxMaService;

    // 注入顾客信息映射器，用于操作顾客信息数据库表
    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    // 注入顾客登录日志映射器，用于记录顾客登录日志
    @Autowired
    private CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * 登录方法，通过微信code获取openid，并查询数据库中对应的顾客信息
     * @param code 微信登录时返回的code
     * @return 如果登录成功，返回顾客ID；否则，可能抛出异常
     */
    @Override
    public Long login(String code) {
        //1 获取code值，使用微信工具包对象，获取微信唯一标识openid
        String openid = null;
        try{
            WxMaJscode2SessionResult sessionInfo= wxMaService.getUserService().getSessionInfo(code);
            openid= sessionInfo.getOpenid();
        }
        catch(Exception e){
            throw new RuntimeException(e);
        }
        //2 根据openid查询数据库，判断是否是第一次登录
        //如果openid不存在返回null,如果存在返回一条记录
        LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerInfo::getWxOpenId,openid);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(wrapper);
        //3 如果第一次登陆，添加信息到用户表
        if (customerInfo == null) {
            customerInfo = new CustomerInfo();
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfo.setWxOpenId(openid);
            customerInfoMapper.insert(customerInfo);
        }

        //4 记录登录日志信息
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        customerLoginLogMapper.insert(customerLoginLog);
        //5 返回用户id
        return customerInfo.getId();


    }

    /**
     * 根据顾客ID获取顾客信息
     * @param customerId 顾客ID
     * @return 顾客信息对象，包含顾客的基本信息和是否绑定手机号的标志
     */
    @Override
    public CustomerLoginVo getCustomerInfo(Long customerId) {
        // 通过顾客ID查询顾客信息
        CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
        // 创建顾客登录信息对象，用于返回顾客信息
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        // 将顾客信息复制到登录信息对象中
        BeanUtils.copyProperties(customerInfo, customerLoginVo);
        // 获取顾客的手机号，判断是否已绑定手机号
        String phone = customerInfo.getPhone();
        boolean isBindPhone = StringUtils.hasText(phone);
        // 设置是否绑定手机号的标志
        customerLoginVo.setIsBindPhone(isBindPhone);
        // 返回顾客登录信息对象
        return customerLoginVo;


    }
    @SneakyThrows
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        try{

            WxMaPhoneNumberInfo  phoneNoInfo =
                    wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
            String phoneNumber= phoneNoInfo.getPhoneNumber();
            Long customerId= updateWxPhoneForm.getCustomerId();
            CustomerInfo customerInfo = customerInfoMapper.selectById(customerId);
            customerInfo.setPhone(phoneNumber);
            customerInfoMapper.updateById(customerInfo);
            return true;
        }
        catch(WxErrorException e){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public String getCustomerOpenId(Long customerId) {
        CustomerInfo customerInfo=this.getOne(new LambdaQueryWrapper<CustomerInfo>().eq(CustomerInfo::getId,customerId).select(CustomerInfo::getWxOpenId));
        return customerInfo.getWxOpenId();
    }
}
